package chen.web.antispam;

import java.util.UUID;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class JudgeImpl implements Judge {
		
	private RegulationGenerator generator;
	
	private Cache store;
	
	protected JudgeImpl(RegulationGenerator generator){
		this.generator = generator;
		
		String random = UUID.randomUUID().toString();
		store = new Cache(random, 10000, false, false, 0, 0);
		CacheManager.create().addCache(store);
	}
	
	@Override
	public void record(Characteristic ch) {
		// TODO Auto-generated method stub	
		Regulation reg = generator.generate();
		if(reg.getMaxTimes() == 0 ){
			return;
		}
		
		Element elem = store.get(ch);
		if(elem == null){
			elem = new Element(ch, new Times());
			elem.setTimeToLive(reg.getTimeRange());
			store.put(elem);
		} else {
			Times times = (Times) elem.getObjectValue();
			times.increase();
			if(reg.getTimeRange() != elem.getTimeToLive()){
				elem.setTimeToLive(reg.getTimeRange());
			}
		}
	}

	@Override
	public boolean against(Characteristic ch) {
		// TODO Auto-generated method stub
		Regulation reg = generator.generate();
		if(reg.getMaxTimes() == 0 ){
			return true;
		}
		
		Element elem = store.get(ch);
		if(elem == null)	return false;
		Times times = (Times) elem.getObjectValue();
		if(times.times < reg.getMaxTimes()){
			return false;
		}
		return true;
	}

	private static class Times{
		private int times;
		
		private Times(){
			this.times = 1;
		}
		
		private void increase(){
			++ times;
		}
	}
}
